package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"net/http"
	"shop_api/forms"
	"shop_api/global"
	"shop_api/global/response"
	"shop_api/proto"
	validator2 "shop_api/validator"
	"strconv"
	"time"
)

type J struct {
	name string `json:"name"`
}

func HandleGrpcErrorToHttp(err error, c *gin.Context) {
	if err != nil {
		if e, ok := status.FromError(err); !ok {
			switch e.Code() {
			case codes.NotFound:
				c.JSON(http.StatusNotFound, gin.H{"msg": e.Message()})
			case codes.Internal:
				c.JSON(http.StatusInternalServerError, gin.H{"msg": "内部错误"})
			case codes.InvalidArgument:
				c.JSON(http.StatusBadRequest, gin.H{"msg": "参数错误"})
			}
		}
	}
}

func GetUserList(ctx *gin.Context) {

	pn := ctx.DefaultQuery("pn", "1")
	page, _ := strconv.Atoi(pn)
	pgs := ctx.DefaultQuery("PgSize", "1")
	pageSize, _ := strconv.Atoi(pgs)

	//defer client.Close()
	//greeterClient := proto.NewUserClient(servClient)
	resp, err := global.UserClient.GetUserList(ctx, &proto.PageInfo{Pn: uint32(page), PgSize: uint32(pageSize)})
	if err != nil {
		fmt.Println(err)
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	result := make([]interface{}, 0)
	for _, v := range resp.Data {

		urespo := response.UserResponse{
			Id:         v.Id,
			Mobile:     v.Mobile,
			NickName:   v.NickName,
			Gender:     v.Gender,
			Birththday: time.Unix(int64(v.BirthDay), 0),
		}

		result = append(result, urespo)
	}
	ctx.JSON(http.StatusOK, result)
}

func Login(ctx *gin.Context) {
	var userForm forms.UserForm

	//注册验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		err := v.RegisterValidation("validator_mobile", validator2.ValidateMobile)
		fmt.Println(err)
		if err != nil {
			panic(err)
		}
	}
	err := ctx.ShouldBindJSON(&userForm)
	if err != nil {
		zap.S().Error("参数错误", err.Error())
	}

	userInfo, err := global.UserClient.GetUserMobile(ctx, &proto.UserMobileReq{Mobile: userForm.Mobile})
	if err != nil {
		zap.S().Error("获取用户信息失败", err.Error())
		return
	}
	//todo password 校验
	ctx.JSON(http.StatusOK, userInfo)
}
